<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 岗位管理
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-button
                        type="primary"
                        icon="el-icon-delete"
                        class="handle-del mr10"
                        @click="delAllSelection"
                >批量删除
                </el-button>
                <el-input v-model="query.id" placeholder="用户名" class="handle-input mr10"></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                <el-button type="primary" icon="el-icon-lx-add" @click="handleAdd()">新建</el-button>

                <!--                excel导出-->


            </div>
            <el-table
                    :data="tableData"
                    border
                    class="table"
                    ref="multipleTable"
                    header-cell-class-name="table-header"
                    @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column prop="id" label="ID" width="55" align="center"></el-table-column>
                <el-table-column prop="postId" label="帖子ID"></el-table-column>
                <el-table-column prop="userId" label="用户ID"></el-table-column>
                <el-table-column prop="reason" label="原因"></el-table-column>
                <el-table-column
                        prop="reportTime"
                        label="举报日期"
                        :formatter="yyyy-MM-dd"
                        align="center"
                ></el-table-column>
                <el-table-column prop="status" label="是否审核">
                    <template slot-scope="scope">
                        <span>{{scope.row.status==0?'未审核':scope.row.status==1?'通过':'不通过'}}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="status" label="是否通过" width="100">
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.status" @change="changUserStatus(scope.row)"></el-switch>
                    </template>
                </el-table-column>

            </el-table>

            <div class="pagination">
                <el-pagination
                        background
                        layout="prev, pager, next"
                        :total="total"
                        :current-page="currentPage"
                        :page-size="pageSize"
                        @current-change="getData">
                </el-pagination>
            </div>
        </div>

        <!--        查询-->
        <el-dialog title="详细信息" :visible.sync="selectVisible" width="50%">

            <el-form-item label="用户名:">
                <el-input></el-input>
            </el-form-item>
            <span slot="footer" class="dialog-footer">
                <el-button @click="selectVisible = false">关闭</el-button>
            </span>
        </el-dialog>

        <!--新建弹出框-->
        <el-dialog title="新建" :visible.sync="addVisible" width="50%">
            <el-form
                    ref="add"
                    :model="add"
                    label-width="80px"
                    class="demo-ruleForm"
                    :rules="rules"

            >
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="add.username"></el-input>

                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="add.password"></el-input>
                </el-form-item>
                <el-form-item label="联系方式" prop="phone">
                    <el-input v-model="add.phone"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="add.email"></el-input>
                </el-form-item>
                <el-form-item label="状态:" :label-width="formLabelWidth" prop="status">
                    <el-select v-model="add.status" autocomplete="off" style="float: left">
                        <el-option label="激活" value="1"></el-option>
                        <el-option label="冻结" value="0"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="权限:" :label-width="formLabelWidth" prop="role">
                    <el-select v-model="add.role" autocomplete="off" style="float: left">
                        <el-option label="管理员" value="admin"></el-option>
                        <el-option label="用户" value="role"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveAdd('add')">确 定</el-button>
            </span>
        </el-dialog>
        <!--        导入excel-->
        <el-dialog
                title="导入excel"
                :visible.sync="dialogVisible"
                width="30%"
                :before-close="handleClose">
            <el-upload
                    class="upload-demo"
                    drag
                    :on-success="uploadAfter"
                    action="http://localhost:9000/forum/user/impUser"
                    multiple>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip" slot="tip">只能上传xls/xlsx文件，且不超过500kb</div>
            </el-upload>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    //导入Stat对应的api
    import { search } from '../../network/fuzzysearch';
    import {reportList} from '../../network/report'
    import { list } from '../../network/usermanage';
    import { userdelete } from '../../network/userdelete';
    import { saveuser } from '../../network/adduser';
    import {changestatus}from '../../network/userstatus'
    import {fileExport}from '../../network/excel'
    //这里要引入表单验证规则
    import valrule from '../../config/validaterule';


    export default {
        name: 'usermanage',
        data() {
            return {

                //switch开关
                authorityvalue: true,
                formLabelWidth: '120px',
                // 新建岗位表单校验
                rules: {
                    username: [{ required: true, message: '用户名', trigger: 'blur' }],
                    password: [{ required: true, message: '密码', trigger: 'blur' }],
                    phone: [{ required: false, message: '联系方式', trigger: 'blur', validator: valrule.validPhone }],
                    email: [{ required: false, trigger: 'blur', validator: valrule.validEmail }],
                    status: [{ required: true, trigger: 'blur' }],
                    role: [{ required: true, trigger: 'blur' }]

                },
                //查询的相关参数
                query: {
                    id: '', //岗位id
                    username: '', //用户名
                    pageIndex: 1, //当前请求页
                    pageSize: 5 //一页显示的数据条数
                },
                //添加的相关参数
                add: {
                    username: '', //岗位名称
                    password: '', //岗位编制
                    phone: '', //岗位类型
                    email: '', //
                    status: '',
                    role: ''
                },
                detailselect: {
                    username: '',
                    phone: '',
                    email: ''

                },
                tableData: [], //获取的数据
                multipleSelection: [],
                delList: [],
                editVisible: false, //编辑弹出框false隐藏，true显示
                addVisible: false, //新建弹出框false隐藏，true显示
                selectVisible: false,
                total: 0,
                pageSize: 10,
                currentPage: 1,
                form: {},
                idx: -1,
                id: -1,
                dialogVisible:false
            };
        },
        created() {
            this.getData();
        },
        methods: {
            //时间格式化
            dateFormat(row, column) {
                var dT = new Date(row.createTime); //row 表示一行数据, dateTime 表示要格式化的字段名称
                return dT.getFullYear() + '-' + (dT.getMonth() + 1) + '-' + dT.getDate();
            },

            //query表单参数判空,如果参数为空字符串或null等则不发送请求
            queryIsNull() {
                let queryForm = {
                    // id: this.query.id, //部门id
                    name: this.query.username, //部门名称
                    pageIndex: this.query.pageIndex, //当前请求页
                    pageSize: this.query.pageSize //一页显示的数据条数
                };

                if (this.query.id.split(' ').join('').length !== 0 && this.query.id !== null && this.query.id !== undefined) {
                    //alert('id不为空');
                    queryForm.id = this.query.id;
                } else {
                    //alert('id为空');
                }

                if (this.query.name(' ').join('').length !== 0 && this.query.name !== null && this.query.name !== undefined) {
                    //alert('id不为空');
                    queryForm.name = this.query.username;
                } else {
                    alert('name为空');
                }

                return queryForm;
            },

            //初始化数据
            getData(currentPage) {
                console.log('表单');
                reportList(currentPage)
                    .then((res) => {
                        // console.log(res.data.records);
                        if (res.code === 200) {
                            console.log(res);
                            this.tableData = res.data.records;
                            this.tableData.forEach(item => {
                                item.status = Boolean(item.status)
                            })

                            this.total = res.data.total;
                            this.pageSize = res.data.size;
                            this.currentPage = res.data.current;
                        } else {
                            this.$message.error('数据获取失败，' + res.msg);
                        }
                    })
                    .catch(() => {
                        this.$message.error('数据获取失败，请在保证网络畅通的情况下检查请求的地址或参数是否正确');
                    });
            },
            // 新建操作
            handleAdd() {
                //alert("即将进入新建页面")
                this.addVisible = true;
            },
            excel(){
                // fileExport()
                //     .then((res) => {
                //
                //         if (res.code === 200) {
                //             console.log(res);
                //            // this.getExcel(res);
                //         } else {
                //             this.$message.error('数据获取失败，' + res.msg);
                //         }
                //     })
                //     .catch(() => {
                //         this.$message.error('数据获取失败，请在保证网络畅通的情况下检查请求的地址或参数是否正确');
                //     });
                window.location.href = "http://localhost:9000/forum/user/export"
            },
            addExcel() {
                this.dialogVisible = true
            },
            uploadAfter() {
                this.getData()
            },
            getExcel(res) {
                require.ensure([], () => {
                    const { export_json_to_excel } = require('../Export2Excel.js')
                    const tHeader = ['用户id', '用户名',"联系方式","邮箱","权限","创建时间","状态"]
                    const filterVal = ['id','username', 'phone','email','role','createTime','status']
                    const list = res
                    const data = this.formatJson(filterVal, list)
                    export_json_to_excel(tHeader, data, '导出列表名称')
                })
            },

            formatJson(filterVal, jsonData) {
                return jsonData.map(v => filterVal.map(j => v[j]))
            },
            // 禁用启用用户
            /**
             * 禁用启用用户
             */
            async changUserStatus(row) {
                // const { data: res } = await this.$http.post(
                //     "forum/user/update" + row.id + "/" + row.status
                // );
                // if (res.code !== 200) {
                //     this.$message.error("更新用户状态失败:" + res.msg);
                //     row.status = !row.status;
                // } else {
                //     var message=row.status?'用户状态已禁用':'用户状态已启用';
                //     this.$notify.success({
                //         title: '操作成功',
                //         message: message,
                //     });
                // }
                this.$confirm('确定要更改状态吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                     alert(row.status);
                    // :disabled="scope.row.role=='admin'?true:false
                    changestatus( row.id, Number(row.status)).then((res) => {
                        console.log(res);
                        if (res.code === 200) {
                            this.$message.success('更改成功');
                            //this.tableData.splice(index, 1);
                            this.getData();
                        } else {
                            this.$message.error('更改失败');
                            this.getData();
                        }
                    });
                });
            },
            // 保存新建
            saveAdd(add) {
                console.log('添加');
                console.log(this.add);
                this.$refs[add].validate((valid) => {
                    if (valid) {
                        this.addVisible = false;
                        saveuser(this.add)
                            .then((res) => {
                                console.log(res);
                                if (res.code === 200) {
                                    this.$message.success('新建用户成功');
                                    this.getData();
                                } else {
                                    this.$message.error('新建用户失败');
                                    this.getData();
                                }
                                this.addVisible = false;
                            })
                            .catch(() => {
                                this.$message.error('数据获取失败，请在保证网络畅通的情况下检查请求的地址是否正确');
                            });
                    } else {
                        this.$message.error('请按照指定格式输入');
                        return false;
                    }
                });
            },
            // 触发搜索按钮
            handleSearch() {
                // this.getData();
                console.log('表单');
                search(1, this.query.id)
                    .then((res) => {
                        console.log(res);
                        if (res.code === 200) {
                            console.log(res);
                            this.tableData = res.data.records;

                            this.pageTotal = res.pageTotal;
                        } else {
                            this.$message.error('数据获取失败，' + res.msg);
                        }
                    })
                    .catch(() => {
                        this.$message.error('数据获取失败，请在保证网络畅通的情况下检查请求的地址或参数是否正确');
                    });
            },
            handleChange(index,row){

            },
            // 删除操作
            handleDelete(index, row) {
                // 二次确认删除
                this.$confirm('确定要删除吗？', '提示', {
                    type: 'warning'
                }).then(() => {

                    userdelete({ 'id': row.id }).then((res) => {
                        console.log(res);
                        if (res.code === 200) {
                            this.$message.success('删除成功');
                            //this.tableData.splice(index, 1);
                            this.getData();
                        } else {
                            this.$message.error('删除失败');
                            this.getData();
                        }
                    });
                });
            },
            // 多选操作
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            delAllSelection() {
                const length = this.multipleSelection.length;
                this.delList = this.delList.concat(this.multipleSelection);
                for (let i = 0; i < length; i++) {
                    let str = this.multipleSelection[i].name;
                    userdelete({ 'id': this.multipleSelection[i].id })
                        .then((res) => {
                            console.log(res);
                            if (res.code === 200) {
                                this.$message.success('删除' + str + '成功');
                            } else {
                                this.$message.success('删除' + str + '失败');
                            }
                        })
                        .catch(() => {
                            this.$message.error('数据获取失败，请在保证网络畅通的情况下检查请求的地址是否正确');
                        });
                }
                this.getData();
                this.multipleSelection = [];
            },
            // 查询操作
            handleSelect(row) {
                console.log(row);
                // alert('查询操作');
                this.selectVisible = true;
            },
            // 分页导航
            handlePageChange(val) {
                alert('请求的页数：' + val);

                // 调用方法：this.$set( target, key, value )
                // target：要更改的数据源(可以是对象或者数组)
                // key：要更改的具体数据
                // value ：重新赋的值
                this.$set(this.query, 'pageIndex', val);
                this.getData();
            },
            handleClose(done) {
                this.$confirm('确认关闭？')
                    .then(_ => {
                        done();
                    })
                    .catch(_ => {});
            }
        }
    };
</script>

<style scoped>
    .handle-box {
        margin-bottom: 20px;
    }

    .handle-select {
        width: 120px;
    }

    .handle-input {
        width: 300px;
        display: inline-block;
    }

    .table {
        width: 100%;
        font-size: 14px;
    }

    .red {
        color: #ff0000;
    }

    .mr10 {
        margin-right: 10px;
    }

    .table-td-thumb {
        display: block;
        margin: auto;
        width: 40px;
        height: 40px;
    }
</style>
